package com.coolgor.axnut.service.wechat.qyh.impl;

import java.io.IOException;
import java.util.Date;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.coolgor.axnut.dao.wechat.qyh.QYHAccessTokenDao;
import com.coolgor.axnut.dto.wechat.qyh.QYHAccessTokenExecution;
import com.coolgor.axnut.entity.wechat.qyh.QYHAccessToken;
import com.coolgor.axnut.enums.wechat.qyh.QYHAccessTokenStateEnum;
import com.coolgor.axnut.service.wechat.qyh.QYHAccessTokenService;
import com.coolgor.axnut.util.wechat.qyh.WechatQYHUtil;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

@Service
public class QYHAccessTokenServiceImpl implements QYHAccessTokenService {
	private static Logger log = LoggerFactory.getLogger(QYHAccessTokenServiceImpl.class);
	
	@Autowired
	private QYHAccessTokenDao qyhAccessTokenDao;

	@Override
	public QYHAccessTokenExecution getQYHAccessToken(Long recordId) {
		QYHAccessToken qyhAccessToken = qyhAccessTokenDao.queryQYHAccessTokenById(recordId);
		if (null == qyhAccessToken) {
			return new QYHAccessTokenExecution(QYHAccessTokenStateEnum.NULL);
		}
		//获取当前时间，并且延长100秒
		Date nowdate = new Date(System.currentTimeMillis()+100*1000);
		//当出现以下情况时
		//1、数据库中的AccessToken记录为空
		//2、数据库中InvalidTime时效时间为空
		//3、这个延长了100秒的时间超出了AccessToken的失效时间
		//则进行重新联网获取AccessToken
		if (	null==qyhAccessToken.getAccessToken() 
				|| null == qyhAccessToken.getInvalidTime() 
				|| nowdate.after(qyhAccessToken.getInvalidTime())) {
			// 根据数据库信息,拼接出访问微信定义好的接口的URL
			// 通过GET方法 ， 标准URL——  https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=ID&corpsecret=SECRECT 
			String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid="+qyhAccessToken.getCorpId()+"&corpsecret="+qyhAccessToken.getSecret();
			String tokenStr = WechatQYHUtil.httpsRequest(url, "GET", null);
			ObjectMapper objectMapper = new ObjectMapper();
			Map<String, Object> tokenMap = null;
			try {
				// 将json字符串转换成相应对象
				tokenMap = objectMapper.readValue(tokenStr, Map.class);
			} catch (JsonParseException e) {
				log.error("获取用户accessToken失败: " + e.getMessage());
				e.printStackTrace();
			} catch (JsonMappingException e) {
				log.error("获取用户accessToken失败: " + e.getMessage());
				e.printStackTrace();
			} catch (IOException e) {
				log.error("获取用户accessToken失败: " + e.getMessage());
				e.printStackTrace();
			}
			if ((int)tokenMap.get("errcode")==0) {
				qyhAccessToken.setAccessToken((String) tokenMap.get("access_token"));
				qyhAccessToken.setExpireTime((int) tokenMap.get("expires_in"));
				qyhAccessToken.setCreateTime(new Date(System.currentTimeMillis()-100*1000));
				qyhAccessToken.setInvalidTime(new Date(System.currentTimeMillis()-100*1000+qyhAccessToken.getExpireTime()*1000));
				int effectNum = qyhAccessTokenDao.updateQYHAccessToken(qyhAccessToken);
				if (effectNum == 1) {
					return new QYHAccessTokenExecution(QYHAccessTokenStateEnum.SUCCESS,qyhAccessToken);
				} else {
					log.error("在数据库中更新企业号accessToken失败。");
					return new QYHAccessTokenExecution(QYHAccessTokenStateEnum.INNER_ERROR);
				}
			} else if (tokenMap == null || !"0".equals(tokenMap.get("errcode"))) {
				log.error("获取企业号accessToken失败。");
				return new QYHAccessTokenExecution(QYHAccessTokenStateEnum.INNER_ERROR);
			}
		}
		return new QYHAccessTokenExecution(QYHAccessTokenStateEnum.SUCCESS,qyhAccessToken);
	}

}
